package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pojo.Order;
import service.OrderManager;
import service.impl.OrderManagerFactory;

/**
 * 下单购买
 * @author WUJA13
 *
 */
public class BuyingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private OrderManager manager;
	
    public BuyingServlet() {
        super();
        manager = OrderManagerFactory.getInstance();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, Order> orderMap = (Map<String, Order>) request.getSession().getAttribute("orderMap");
		Set<String> orderSet = orderMap.keySet();
		List<Order> list  =new ArrayList<Order>();
		
		Logger logger = Logger.getLogger(BuyingServlet.class);
		
		for(String it:orderSet){
			Order order = orderMap.get(it);
			System.out.println("即将提交的订单： "+order);
			logger.info("即将提交的订单： "+order);
			list.add(order);
		}
		
		if(list.size()==0){
			 //回到购物车页
			 logger.info("订单为空，无法提交！");
			 request.setAttribute("msg", "订单为空，无法提交！");
			 request.getRequestDispatcher("ShoppingCartServlet").forward(request, response);
			 
			return;
		}
		
		if(manager.buy(list)>0){
			///成功提交订单。购买成功
			///清空session中的购物车
			 request.getSession().setAttribute("orderMap", new HashMap<String,Order>());
			request.getSession().setAttribute("bid", null);
			request.getSession().setAttribute("bname", null);
//			response.sendRedirect("../success.html");
			 //回到购物车页
			 logger.info("成功提交订单，购买成功！");
			 request.setAttribute("msg", "成功提交订单，购买成功！");
			 request.getRequestDispatcher("ShoppingCartServlet").forward(request, response);
			 
		}else{
			///购买失败
			 //回到购物车页
			 logger.info("购买失败!");
			 request.setAttribute("msg", "购买失败！");
			 request.getRequestDispatcher("ShoppingCartServlet").forward(request, response);
		}
		
	}

}
